package com.juntos.quizes.canadaDay.form {
	
	import caurina.transitions.Equations;
	import caurina.transitions.Tweener;
	import caurina.transitions.properties.TextShortcuts;
	
	import com.ghostmonk.form.FormField;
	import com.ghostmonk.form.FormFieldCollection;
	import com.ghostmonk.form.model.FormLocalizationStrings;
	import com.ghostmonk.form.utils.FieldRestrictions;
	import com.ghostmonk.form.utils.RegExFormEvaluations;
	import com.ghostmonk.text.EmbeddedText;
	import com.ghostmonk.utils.SequenceCounter;
	import com.juntos.quizes.canadaDay.events.FormEvent;
	import com.juntos.quizes.canadaDay.interactiveElements.NavigationButton;
	import com.juntos.quizes.canadaDay.model.UserInfo;
	
	import flash.display.DisplayObject;
	import flash.events.MouseEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
    
    [Event(name="formSubmit",type="com.juntos.quizes.canadaDay.events.FormEvent")]
    
    /**
     *@author ghostmonk - 2009-06-24
     */
    public class UserForm extends UserFormAsset {
        
        private var _sequenceCounter:SequenceCounter;
        private var _formFields:FormFieldCollection;
        private var _formTitle:EmbeddedText;
        private var _submit:NavigationButton;
        private var _filters:Array;
        private var _endpoint:String;       
        
        /**
         * 
         * @param strings - object containing strings to be used to format the form
         * 
         */
        public function UserForm( strings:FormLocalizationStrings, filters:Array, endPoint:String, btnLabel:String ) {
        	
        	TextShortcuts.init();
        	
        	_filters = filters;
        	_endpoint = endPoint;
        	
        	var regExEvals:RegExFormEvaluations = new RegExFormEvaluations();
        	var restrict:FieldRestrictions = new FieldRestrictions();
        	_sequenceCounter = new SequenceCounter( 0, 1 );
        	_formFields = new FormFieldCollection();
        	_submit = new NavigationButton( submitBtn, onSubmit, btnLabel );
        	
        	title.text = strings.title;
        	
        	_formFields.addField( 
        	   createFormField( strings.firstName, strings.firstNameError, firstName, null, true, restrict.alpha + restrict.frenchChars, 40 ) 
        	);
        	
        	_formFields.addField( 
        	   createFormField( strings.lastname, strings.lastNameError, lastName, null, true, restrict.alpha + restrict.frenchChars, 40 ) 
        	);
        	
        	_formFields.addField( 
        	   createFormField( strings.email, strings.emailError, email, regExEvals.email, true, restrict.email, 50 ) 
        	);
        	
        	_formFields.addField( 
        	   createFormField( strings.age, "", age, null, false, restrict.numeric, 2 ) 
        	);
        	
        	_formFields.addField( 
        	   createFormField( strings.postalCode, strings.postalCodeError, postalCode, regExEvals.postalCode, true, restrict.alpha + restrict.numeric + " ", 7 ) 
        	);
        	
        	_sequenceCounter = null;
        	regExEvals = null;
        	restrict = null;
        	
        	
        	if( CanadaDayQuiz.DEBUG ) {
        		
        		firstName.field.text = "REMEMBER TO FLIP THE SWITCH";
        		lastName.field.text = "REMEMBER TO FLIP THE SWITCH";
        		email.field.text = "nicholas@ghostmonk.com";
        		age.field.text = "123";
        		postalCode.field.text = "m2m2m2";
        		
        	}
        	
        	
        }
        
        
        
        
        
        public function buildIn():void {
        	
        	var output:String = title.text;
        	title.text = "";
        	Tweener.addTween( title, { _text:output, time:0.4, delay:0.4, transition:Equations.easeNone } );
        	buildInTween( firstName, 0 );
        	buildInTween( lastName, 0.1 );
        	buildInTween( email, 0.2 );
        	buildInTween( age, 0.3 );
        	buildInTween( postalCode, 0.4 );
        	buildInTween( submitBtn, 0.5 );
        	
        }
        
        
        
        public function buildOut():void {
        	
            buildOutTween( firstName );
            buildOutTween( lastName );
            buildOutTween( email );
            buildOutTween( age );
            buildOutTween( postalCode );
            buildOutTween( submitBtn );
            
            Tweener.addTween( 
                title, { 
                    _text:"", 
                    time:0.3, 
                    transition:Equations.easeNone, 
                    onComplete:parent.removeChild, 
                    onCompleteParams:[this] 
                } 
            );
        	
        }
        
        
        
        private function buildInTween( item:DisplayObject, delay:Number ):void {
        	
        	var dest:Number = item.y;
        	item.y = dest - 20;
        	item.alpha = 0;
        	Tweener.addTween( item, { alpha:1, time:0.5, y:dest, delay:delay } );   
        	
        }
        
        
        
         private function buildOutTween( item:DisplayObject ):void {
            
            Tweener.addTween( 
               item, {
                   alpha:0,
                   time:0.3,
                   y:item.y + 20
               }
            );   
            
        }
        
                
        
        
        private function createFormField( label:String, error:String, asset:FormFieldAsset, eval:RegExp, isRequired:Boolean, restrict:String, length:int ):FormField {
        	
        	var field:FormField = new FormField( _sequenceCounter.increment, label, error, asset.field, asset.background, eval );
        	field.isRequired = isRequired;
        	field.filters = _filters;
        	field.restriction = restrict;
        	field.maxLength = length;
        	return field;
        	
        }
        
        
        
        private function onSubmit( e:MouseEvent ):void {
            
            _formFields.reset();
            var field:FormField = _formFields.currentField;
            
            while( field ) {
                field = evaluateAndReturnNext( field );
            }
            
            if( errorTxt.text == "" ) {
            	sendResults();
            }
            
        }
        
        
        
        private function evaluateAndReturnNext( field:FormField ):FormField {
        	
        	var output:FormField = field;
        	
        	errorTxt.text = "";
        	
        	if( output.isValid ) {
                output = _formFields.nextField;
            }
            else {
                errorTxt.text = output.errorText;
                output.selectAll( stage );
                output = null;
            } 
            
            return output;
        	
        }
        
        
        
        private function sendResults():void {
        	
        	_submit.disable();
        	var userInfo:UserInfo = new UserInfo();
        	var urlLoader:URLLoader = new URLLoader();
            
            var request:URLRequest = new URLRequest( _endpoint );
            request.method = URLRequestMethod.POST;
            
            var vars:URLVariables = new URLVariables();
            vars.first_name = userInfo.firstName = _formFields.getFieldByIndex( 0 ).textField.text;
            vars.last_name = userInfo.lastName = _formFields.getFieldByIndex( 1 ).textField.text;
            vars.email = userInfo.email = _formFields.getFieldByIndex( 2 ).textField.text;
            vars.age = userInfo.age = _formFields.getFieldByIndex( 3 ).textField.text;
            vars.postal_code = userInfo.postalCode = _formFields.getFieldByIndex( 4 ).textField.text;
            
            request.data = vars;
            
            if( !CanadaDayQuiz.DEBUG ) {
                //urlLoader.load( request );
            }
            
            dispatchEvent( new FormEvent( FormEvent.FORM_SUBMIT, userInfo ) );
            buildOut();
            
        	
        }
        
        
    }
}